<template>
  <el-dialog title="上传图片" :visible.sync="show" width="80%" :before-close="close">
    <el-upload
      action=""
      :http-request="upload">
      <el-button size="small" type="primary">选择图片</el-button>
    </el-upload>
    <el-button :loading="uploading" v-if="originFileName!=''" size="small" @click="onCropper"
               style="position:absolute;right: 20px;z-index: 1"
               type="primary">上传

    </el-button>
    <vueCropper
      style="height: 350px"
      ref="cropper"
      :img="option.img"
      :outputSize="option.size"
      :outputType="option.outputType"
      :autoCrop="option.autoCrop"
      :centerBox="option.centerBox"
      :fixed="option.fixed"
      :fixedNumber="option.fixedNumber"
      :infoTrue="option.infoTrue"
      :full="option.full"
    ></vueCropper>


  </el-dialog>
</template>

<script>
  import {VueCropper} from 'vue-cropper'
  import Upload from '../../api/upload'
  import axios from 'axios'

  export default {
    name: "preSingleImage",
    props: {
      "show": Boolean,
      autoCrop: {type: Boolean, default: true},
      fixedNumber: {
        type: Array, default: function () {
          return []
        }
      }
    },
    data() {
      return {
        option: {
          img: '/static/img/avator.7b68a17.gif',
          outputType: "png",
          size: 1,
          autoCrop: this.autoCrop,
          centerBox: true,
          fixed: this.fixedNumber.length > 0,
          fixedNumber: this.fixedNumber,
          infoTrue: true,
          full: true
        },
        originFileName: '',
        visible: false,
        uploading: false
      }
    },
    components: {
      VueCropper,
    },
    methods: {
      upload(e) {
        var file = e.file
        this.originFileName = e.file.name
        var reader = new FileReader();
        reader.onload = e => {
          let data;
          if (typeof e.target.result === "object") {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]));
          } else {
            data = e.target.result;
          }
          this.option.img = data;

        };
        // 转化为base64
        // reader.readAsDataURL(file)
        // 转化为blob
        reader.readAsArrayBuffer(file);
      },
      async onCropper() {
        var _this = this
        this.uploading = true
        if (!this.autoCrop) {
          let blob = await fetch(this.option.img).then(r => r.blob());
          Upload.uploadFile(blob, _this.originFileName, _this.originFileName).then(res => {
            if (res.data.succ) {
              _this.$message({
                message: '上传成功',
                type: 'success'
              })
              _this.$emit('success', res.data.data)
            } else {
              _this.$message("上传失败")
            }
            _this.uploading = false
          })
        } else {
          this.$refs.cropper.getCropData(function (data) {
            let file = _this.convertBase64UrlToBlob(data)
            file.name = _this.originFileName
            Upload.uploadFile(file, _this.originFileName, _this.originFileName).then(res => {
              if (res.data.succ) {
                _this.$message({
                  message: '上传成功',
                  type: 'success'
                })
                _this.$emit('success', res.data.data)
              }

            })
          })
        }
      },
      close() {
        this.$emit('update:show', false)
      },
      convertBase64UrlToBlob(urlData) {
        let bytes = window.atob(urlData.split(',')[1]);//去掉url的头，并转换为byte
        //处理异常,将ascii码小于0的转换为大于0
        let ab = new ArrayBuffer(bytes.length);
        let ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
          ia[i] = bytes.charCodeAt(i);
        }
        return new Blob([ab], {type: 'image/png'});
      }

    }
  }
</script>

<style scoped>

</style>
